<?php
/**
 * 程序及异常类
 * * Created by lni_wang.
 * Product: PhpStorm
 * Date: 2017/4/18 13:49
 * File: SysException.php
 */
class SysException extends Exception
{
    private $__data = [];
    private $__error_list = [
        30001 => '缺少参数',
        30002 => '数据库配置信息错误',
        30003 => '参数{0} 未定义',
        30004 => '数据库执行失败',
        30005 => '信息错误',
        30006 => '数据已经存在',

        40001 => '用户信息已经存在',
        40002 => '用户信息不存在',
        40003 => '登录密码错误',
        40004 => '信息数据不存在',
        40005 => '证书验证失败',
        40006 => 'access token 有效时间已过期',
        40007 => '网站已经存在',
        40008 => '网站链接格式错误, 必填添加包含域名的完整url地址',
    ];

    function __construct($message, array $replace=[], $previous = null){
        if(isset($this->__error_list[$message])){
            $code       = $message;
            $message    = $this->__error_list[$message];
            if($replace){
                $message = $this->ReplaceErrorMessage($message, $replace);
            }
        }else{
            $code       = 99998;
        }
        parent::__construct($message, $code, $previous);
    }

    function getErrorToArray()
    {
        return [
            'code'    => $this->getCode(),
            'message' => $this->getMessage(),
            'data'    => $this->getData(),
        ];
    }

    function getData()
    {
        return $this->__data;
    }

    function  setData(array $data)
    {
        $this->__data = $data;
    }

    function ReplaceErrorMessage($message, $replace =[])
    {
        $search = [];
        foreach ($replace as $key => $val){
            $search[] = '{' . $key . '}';
        }
        $message = str_replace(
            $search, array_values($replace), $message
        );
        unset($search);
        return $message;
    }
}